<template>
    <div id="add-edit-jha">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="120px" :rules="rules">
                <el-row :gutter="2">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险分区">
                            <el-select v-model="riskAreaId" filterable class="m-2" placeholder="选择风险分区"  @change="riskAreaChange">
                                <el-option v-for="item in riskAreaList" :key="item.id" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="riskAreaId">
                        <el-form-item label="风险分析单元" prop="l_AnalysisUnitId">
                            <el-select 
                                v-model="ruleForm.l_AnalysisUnitId" 
                                filterable 
                                class="m-2" 
                                placeholder="选择分析单元" 
                                value-key="id"
                                popper-class="set-select"
                                :popper-append-to-body="false"
                            >
                                <el-option
                                    v-for="item in unitOptions"
                                    :key="item.id"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="作业活动名称" prop="v_WorkName">
                            <el-input v-model="ruleForm.v_WorkName" placeholder="作业活动名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="潜在事故类型">
                            <el-input type="textarea" autosize v-model="ruleForm.v_AccidentType" placeholder="潜在事故类型" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="事故原因分析">
                            <el-input type="textarea" autosize v-model="ruleForm.v_AccidentCause" placeholder="事故原因分析" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="工程技术">
                            <el-input type="textarea" autosize v-model="ruleForm.v_ControlMeasureProject" placeholder="工程技术" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="管理措施">
                            <el-input type="textarea" autosize v-model="ruleForm.v_ControlMeasureManage" placeholder="管理措施" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="培训教育">
                            <el-input type="textarea" autosize v-model="ruleForm.v_ControlMeasureEdu" placeholder="培训教育" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="个体防护">
                            <el-input type="textarea" autosize v-model="ruleForm.v_ControlMeasurePerson" placeholder="个体防护" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="应急措施">
                            <el-input type="textarea" autosize v-model="ruleForm.v_ControlMeasureEmergency" placeholder="应急措施" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险评价-L">
                            <el-input type="number" min="0" v-model="ruleForm.n_RiskAssessmentL" placeholder="风险评价-L" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险评价-E">
                            <el-input type="number" min="0" v-model="ruleForm.n_RiskAssessmentE" placeholder="风险评价-E" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险评价-C">
                            <el-input type="number" min="0" v-model="ruleForm.n_RiskAssessmentC" placeholder="风险评价-C" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险评价-D">
                            <el-input type="number" min="0" v-model="ruleForm.n_RiskAssessmentD" placeholder="风险评价-D" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险程度">
                            <el-select 
                                filterable
                                v-model="ruleForm.n_RiskLevel" 
                                class="m-2" 
                                placeholder="选择风险程度" 
                                popper-class="set-select"
                                :popper-append-to-body="false"
                            >
                                <el-option
                                    v-for="item in levelOptions"
                                    :key="item.id"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="纠正措施">
                            <el-input type="textarea" autosize v-model="ruleForm.v_CorrectiveMeasure" placeholder="纠正措施" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label-width="140px" label="工作步骤或工作内容">
                            <el-input type="textarea" autosize v-model="ruleForm.v_WorkContent" placeholder="工作步骤或工作内容" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button type="primary" :disabled="repeatDis" :loading="repeatDis" @click="submitForm(ruleFormRef)">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue';
import { FormInstance, FormRules , ElMessage, ElButton, ElCol, ElDatePicker, ElDialog, ElDivider, ElForm, ElFormItem, ElInput, ElOption, ElRadio, ElRow, ElSelect, ElTable, ElTableColumn } from 'element-plus';
import { 
    SMSDCJHALECAdd,
    SMSDCJHALECUpdate,
    SMSDCRiskPartitionList, SMSDCAnalysisUnitList
} from '/@/api/centerControl/sms';
import { any } from 'video.js/dist/types/utils/events';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    l_AnalysisUnitId: any, // 区域/工艺过程(风险管控分析单元Id)
    v_WorkName: String, // 作业活动名称
    v_WorkContent: String, // 工作步骤或工作内容
    v_AccidentType: String, // 潜在事故类型
    v_AccidentCause: String, // 事故原因分析
    v_ControlMeasureProject: String, // 已有控制措施-工程技术
    v_ControlMeasureManage: String, // 已有控制措施-管理措施
    v_ControlMeasureEdu: String, // 已有控制措施-培训教育
    v_ControlMeasurePerson: String, // 已有控制措施-个体防护
    v_ControlMeasureEmergency: String, // 已有控制措施-应急措施
    n_RiskAssessmentL: Number | any, // 风险评价-L
    n_RiskAssessmentE: Number | any, // 风险评价-E
    n_RiskAssessmentC: Number | any, // 风险评价-C
    n_RiskAssessmentD: Number | any, // 风险评价-D
    n_RiskLevel: Number, // 风险等级
    v_CorrectiveMeasure: String, // 纠正措施
}
export default defineComponent( {
    name: 'add-edit-jha',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        },
        commonInfo: {
            type: Array,
            default: () => [],
        },
    },
    setup(props,ctx){
        const titleCon = ref();
        const ruleFormRef = ref();
        const unitOptions = ref();


        const riskAreaId = ref()
        const riskAreaList = ref([])

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 区域/工艺过程(风险管控分析单元Id)
            l_AnalysisUnitId: [
				{ required: true, message: '请选择分析单元', trigger: 'change' },
			],
            // 作业活动名称
            v_WorkName: [
				{ required: true, message: '请输入作业活动名称', trigger: 'blur' },
			],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick();
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
                    riskAreaId.value = ''
            ctx.emit('cancelUseClick')
        }


        const riskAreaChange = async (id: number) => {
            unitOptions.value = []
           state.ruleForm.l_AnalysisUnitId = ''
            const res = await SMSDCAnalysisUnitList({ l_RiskPartitionId: id })
            unitOptions.value = res.data.map((item: any) => {
                return {
                    value: item.id,
                    label: item.v_Name
                }
            })
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!riskAreaId.value) return ElMessage.error('请选择风险分区')
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    state.repeatDis = true;
                    let param = toRaw(state.ruleForm);
                    try{
                        let res: any;
                        if(props.repairInfo !== ''){
                            res = await SMSDCJHALECUpdate(param);
                        }else{
                            res = await SMSDCJHALECAdd(param);
                        }
                        if(res.success){
                            state.repeatDis = false;
                            ctx.emit('controlUseClick');
                            ctx.emit('updateData');
                        }else{
                            state.repeatDis = false;
                            ctx.emit('controlUseClick');
                        }
                    }catch(error){ state.repeatDis = false; }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                state.repeatDis = false;
                // unitOptions.value = props.commonInfo;
                if(props.repairInfo !== ''){
                    titleCon.value = '编辑';
                    state.ruleForm = JSON.parse(props.repairInfo);
                }else{
                    titleCon.value = '新增';
                    state.ruleForm = {
                        l_AnalysisUnitId: '', // 区域/工艺过程(风险管控分析单元Id)
                        v_WorkName: '', // 作业活动名称
                        v_WorkContent: '', // 工作步骤或工作内容
                        v_AccidentType: '', // 潜在事故类型
                        v_AccidentCause: '', // 事故原因分析
                        v_ControlMeasureProject: '', // 已有控制措施-工程技术
                        v_ControlMeasureManage: '', // 已有控制措施-管理措施
                        v_ControlMeasureEdu: '', // 已有控制措施-培训教育
                        v_ControlMeasurePerson: '', // 已有控制措施-个体防护
                        v_ControlMeasureEmergency: '', // 已有控制措施-应急措施
                        n_RiskAssessmentL: '', // 风险评价-L
                        n_RiskAssessmentE: '', // 风险评价-E
                        n_RiskAssessmentC: '', // 风险评价-C
                        n_RiskAssessmentD: '', // 风险评价-D
                        n_RiskLevel: 0, // 风险等级
                        v_CorrectiveMeasure: '', // 纠正措施
                    }
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        onMounted(async () => {
            riskAreaList.value = []
            const res = await SMSDCRiskPartitionList({})
            riskAreaList.value = res.data.map((item: any) => {
                return {
                    label: item.v_Name,
                    value: item.id,
                }
            })

        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            unitOptions,
            levelOptions: [
                {id: 0, label: '低风险', value: 0},
                {id: 1, label: '一般风险', value: 1},
                {id: 2, label: '较大风险', value: 2},
                {id: 3, label: '重大风险', value: 3},
            ],
            riskAreaList, riskAreaId, riskAreaChange
        }
    },
} )
</script>
<style scoped lang="scss">
:deep(.el-cascader){
    width: 100%;
}
:deep(.el-select){
    width: 100%!important;
}
:deep(.el-input){
    width: 100%;
}
</style>